<template>
  <!--    实名认证的组件的结构-->
    <el-card class="box-card">
        <template #header>
            <div class="card-header">
                <h3>实名信息</h3>
            </div>
        </template>

        <div class="tip">
            <p>
                <el-icon>
                    <InfoFilled/>
                </el-icon>
                完成实名认证后才能添加就诊人，正常进行挂号，为了不影响后续步骤，建议提前实名认证
            </p>
        </div>

        <!--        卡片的底部部分：认证成功||认证失败-->
        <!--        1、认证成功-->
        <el-descriptions
                v-if="userInfo.authStatus == 1"
                class="margin-top"
                :column="1"
                border
                size="small"
                style="margin: 20px auto"
        >
            <el-descriptions-item width="15px" label-align="center">
                <template #label>
                    <div class="cell-item">
                        用户姓名
                    </div>
                </template>
                {{ userInfo.name }}
            </el-descriptions-item>
            <el-descriptions-item width="15px" label-align="center">
                <template #label>
                    <div class="cell-item">
                        证件类型
                    </div>
                </template>
                {{ userInfo.certificatesType == '10' ? '身份证' : '户口本' }}
            </el-descriptions-item>
            <el-descriptions-item width="15px" label-align="center">
                <template #label>
                    <div class="cell-item">
                        证件号码
                    </div>
                </template>
                {{ userInfo.phone }}
            </el-descriptions-item>
        </el-descriptions>

        <!--        2、未验证-->
        <el-form
                v-if="userInfo.authStatus ==0"
                label-width="80px"
                style="width:60%;margin: 20px auto"
                :model="params"
                :rules="rules"
                ref="form"
        >
            <el-form-item prop="name" label="用户姓名">
                <el-input  v-model="params.name" placeholder="请输入用户姓名！"/>
            </el-form-item>
            <el-form-item prop="certificatesType" label="证件类型">
                <el-select v-model="params.certificatesType" style="width: 100%" placeholder="请选择证件类型">
                    <el-option :label="item.name" :value="item.value" v-for="(item,index) in arrType" :key="index"/>
                </el-select>
            </el-form-item>
            <el-form-item prop="certificatesNo" label="证件号码">
                <el-input v-model="params.certificatesNo" placeholder="请输入证件号码"/>
            </el-form-item>
            <el-form-item prop="certificatesUrl" label="上传证件">
                <!--                action:文件上传接口
                                    limit:照片墙约束图片的个数
                                    on-exceed:超出约束数量的钩子
                                    on-success:文件上传成功的钩子
                                    on-preview:预览的钩子
                                    on-remove:删除的钩子
                -->
                <el-upload
                        ref="upload"
                        list-type="picture-card"
                        action="/api/oss/file/fileUpload?fileHost=userAuah"
                        :limit="1"
                        :on-exceed="exceedHandle"
                        :on-success="successHandle"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove"
                >
                    <img style="width: 100%;height: 100%" src="@/assets/images/auth_example.png" alt=""/>
                </el-upload>
                <el-dialog v-model="dialogVisible">
                    <img w-full v-if="params?.certificatesUrl" style="width: 100%;height: 100%" alt="Preview Image"
                         :src="params.certificatesUrl"/>
                </el-dialog>
            </el-form-item>
            <el-form-item>
                <el-button @click="submit" type="primary">提交</el-button>
                <el-button @click="reset">重写</el-button>
            </el-form-item>
        </el-form>
    </el-card>

</template>

<script setup lang="ts">

import {InfoFilled, Plus} from "@element-plus/icons-vue";
import {onMounted, reactive, ref} from "vue";
import {reqUserInfo, reqUserCertation, reqCertificationType} from "@/api/user";
import type {UserParams, DocumentArr, UserInfoResponseData, DocumentTypeResponseData} from "@/api/user/type.ts";
import {ElMessage} from "element-plus";

//存储用户信息
let userInfo: any = ref({})
//存储证件类型数组
let arrType = ref<DocumentArr>([])
//收集表单验证的信息
let params = reactive<UserParams>({
    "certificatesNo": '',
    "certificatesType": '',
    "certificatesUrl": '',
    "name": ''
})
//控制兑换框的显示与隐藏
let dialogVisible = ref<boolean>(false)
//上传组件实例
let upload = ref()
//获取表单实例
let form = ref()

onMounted(async () => {
    //获取证件类型
    await getDocumentType()
    //获取用户信息
    await getUserInfo()
})

//获取用户信息的方法
const getUserInfo = async () => {
    let result: UserInfoResponseData = await reqUserInfo()
    if (result.code == 200) {
        userInfo.value = result.data
    }
}

//获取证件类型的方法
const getDocumentType = async () => {
    let result: DocumentTypeResponseData = await reqCertificationType()
    if (result.code == 200) {
        arrType.value = result.data
    }
}


//超出数量的钩子
const exceedHandle = () => {
    ElMessage({
        type: "error",
        message: '图片只能上传一张'
    })
}


//图片上传成功的钩子
const successHandle = (response: any) => {
    //将校验结果去掉
    form.value.clearValidate('certificatesUrl')
    //收集上传成功的图片地址
    //response:上传图片返回的信息
    params.certificatesUrl = response.data
    //uploadFile:上传图片的信息对象
    //uploadFiles：上传的所有的图片的信息对象
}

//预览的钩子函数
const handlePictureCardPreview = () => {
    //触发预览的钩子的时候，对话框显示
    dialogVisible.value = true
}

//删除图片的的钩子
const handleRemove = () => {
    params.certificatesUrl = ''
}

//重写的函数
const reset = () => {
    //清空数据
    Object.assign(params)
    form.value.resetFields()
    upload.value.resetFields()
}

//提交按钮的回调
const submit = async () => {
     await form.value.validate()
    try {
        //认证成功
        await reqUserCertation(params)
        console.log(params)
        ElMessage({
            type: "success",
            message: '认证成功'
        })
        //重新获取用户信息
        await getDocumentType()
    } catch (error) {
        ElMessage({
            type: "error",
            message: error.message
        })
    }
}

const validatorName = (rule:any,value:any,callBack:any)=>{
    //rule:当前校验字段的校验对象
    //value:要校验的文本内容
    //callBack：封装函数，自定义返回信息
    let reg = /^[\u4E00-\u9FA5]{2,10}(·[\u4E00-\u9FA5]{2,10}){0,2}$/;
    if(reg.test(value)){
        callBack()
    }else {
        callBack(new Error("请输入正确的中国人名字"))
    }
}
const validatorType = (rule:any,value:any,callBack:any)=>{
    if(value=="10"||value=="20"){
        callBack()
    }else {
        callBack(new Error("请选择证件类型"))
    }
}
const validatorNo = (rule:any,value:any,callBack:any)=>{
    let reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    let reg2 =/^[a-zA-Z0-9]{3,21}$/
    if(reg.test(value)||reg2.test(value)){
        callBack()
    }else {
        callBack(new Error("请输入正确的证件号码"))
    }
}
const validatorUrl = (rule:any,value:any,callBack:any)=>{
    if(value.length){
        callBack()
    }else {
        callBack(new Error("请上传正确的证件照图片"))
    }
}

//表单校验的规则对象
const rules = {
    name:[{
            required: true,
            validator:validatorName
        }],
    certificatesType:[{
            required: true,
            validator:validatorType
        }],
    certificatesNo:[{
            required: true,
            validator:validatorNo
        }],
    certificatesUrl:[{
            required: true,
            validator:validatorUrl
        }],
}

</script>


<style scoped lang="scss">
.box-card {
  .tip {
    color: #7f7f7f;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 13px;
  }
}
</style>